package com.monkeyboy.controller;

import com.monkeyboy.service.GenService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 代码生成工具
 *
 * @Author Gavin
 * @date 2020.07.10 11:25
 */
@RestController
public class GenController {
    @Autowired
    private GenService genService;

    /*
    生成代码
     */
    @CrossOrigin
    @GetMapping("/genCode/{tableName}")
    public void genCode(@PathVariable String tableName, HttpServletResponse response) throws Exception {
        byte[] data = genService.generatorCode(tableName);
        //可以直接存到磁盘上
//        File file = new File("d:/gen-code/code.zip");
//        OutputStream out = new FileOutputStream(file);
//        out.write(data);
//        out.flush();
//        out.close();
        genCode(response, data);
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}
